//
//  ExercisesQuestionChoiceViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/8.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "ExercisesQuestionChoiceViewController.h"
#import "ExercisesQuqestionChoiceItemCell.h"
#import "ExercisesQuqestionChoiceMainTitleCell.h"
#import "ExercisesQuqestionChoiceOtherTitleCell.h"
#import "ExercisesAnswerAnalysisCell.h"
@interface ExercisesQuestionChoiceViewController ()<UITableViewDelegate,UITableViewDataSource,ExercisesQuqestionChoiceItemCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)ExercieseQuestionItemModel *currentItemModel;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,assign)CGFloat timeSource;

@property (nonatomic,strong)UIView *coverView;
@property (nonatomic,strong)UIImageView *coverCardNextImgView;
@property (nonatomic,strong)UIImageView *coverRemoveImgView;
@property (nonatomic,strong)UIImageView *coverSelectedImgView;


@property (nonatomic,assign)BOOL isFinishItem;
@property (nonatomic,assign)BOOL isFinishTitle;
@property (nonatomic,assign)BOOL isFinishAnlzy;
@property (nonatomic,assign)BOOL isFinishCorrect;


@end

@implementation ExercisesQuestionChoiceViewController




- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    self.isHideNavBar = YES;
    

    // Do any additional setup after loading the view.
}


- (void)setUI{
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 100;
        _tableView.estimatedSectionFooterHeight = .0f;
        _tableView.estimatedSectionHeaderHeight = .0f;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (void)updateQuestionItem:(ExercieseQuestionItemModel *)itemModel atIndex:(NSInteger)index{
    
    
    if (self.currentItemModel == nil) {
        self.currentItemModel = itemModel;
        self.isFinishTitle = ![itemModel.title cl_html5];
        self.isFinishCorrect = ![itemModel.correct cl_html5];
        self.isFinishAnlzy = ![itemModel.analyze cl_html5];
        
        self.isFinishItem = YES;
        [itemModel.items enumerateObjectsUsingBlock:^(ExercisesQuestionChoiceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.content cl_html5]) {
                self.isFinishItem = NO;
                *stop = YES;
            }
        }];
        [self.tableView reloadData];
    }
    
    BOOL isFirst = [[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstAnswerCard"] boolValue];
    
    if (!isFirst && index == 1) {
        [[UIApplication sharedApplication].keyWindow addSubview:self.coverView];
    }
}

- (void)startTimer{
    
    if (self.timer == nil){
        self.timeSource = self.currentItemModel.answerTime;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addAnswerTime) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

- (void)addAnswerTime{
    self.timeSource+=0.01;
}

- (void)endTimer{
    self.currentItemModel.answerTime = self.timeSource;
    [self.timer invalidate];
    self.timer = nil;
}
- (void)setupCoverView{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        self.coverView.backgroundColor = RGBA(0, 0, 0, 0.7);
  
        self.coverCardNextImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"exerciese_card_tag_next"]];
        [self.coverView addSubview:self.coverCardNextImgView];
        [self.coverCardNextImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.coverView).offset(-32);
            make.top.equalTo(self.coverView).offset(kNavBarHeight + 5);
        }];
        self.coverRemoveImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_help_tag"]];
        [self.coverView addSubview:self.coverRemoveImgView];
        [self.coverRemoveImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.coverView).offset(-(200 + GK_SAVEAREA_BTM));
            make.right.equalTo(self.coverView).offset(-18);
        }];
        
        self.coverRemoveImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeHelpView)];
        [self.coverRemoveImgView addGestureRecognizer:tap];
        
        self.coverSelectedImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"exercises_cover_select_tag"]];
        [self.coverView addSubview:self.coverSelectedImgView];
        [self.coverSelectedImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.coverView);
        }];
        
        // 第一个路径
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0,kScreenW, kScreenH)];
        // 透明path
        UIBezierPath *path2 = [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(kScreenW - 95, GK_STATUSBAR_HEIGHT + 8,90,32) cornerRadius:16] bezierPathByReversingPath];
        [path appendPath:path2];
        // 绘制透明区域
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = path.CGPath;
        [self.coverView.layer setMask:shapeLayer];
    });
}

- (void)removeAllHelpView{
    [self.coverView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.coverView removeFromSuperview];
}
- (void)removeHelpView{
    [self.coverView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.coverView removeFromSuperview];
    [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:@"isFirstAnswerCard"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.currentItemModel == nil) {
        return 0;
    }
    if (self.currentItemModel.answerItem != nil) {
        return 4;
    }
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return self.currentItemModel.items.count;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self)weakSelf = self;
    if (indexPath.section == 0) {
        ExercisesQuqestionChoiceMainTitleCell *cell = [ExercisesQuqestionChoiceMainTitleCell cellWithTableView:tableView];
        [cell setModel:self.currentItemModel];
        return cell;
    }
    if (indexPath.section == 1) {
        ExercisesQuqestionChoiceOtherTitleCell *cell = [ExercisesQuqestionChoiceOtherTitleCell cellWithTableView:tableView];
        [cell setModel:self.currentItemModel];
        cell.updateTableViewFrame = ^{
            weakSelf.isFinishTitle = YES;
            [weakSelf finishRefreshTableView];
        };
        return cell;
    }
    
    if (indexPath.section == 2) {
        ExercisesQuqestionChoiceItemCell *cell = [ExercisesQuqestionChoiceItemCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setQuqestionChoiceModel:self.currentItemModel.items[indexPath.row] answerModel:self.currentItemModel.answerItem correntModel:self.currentItemModel];
        return cell;
    }
    
    if (indexPath.section == 3) {
        ExercisesAnswerAnalysisCell *cell = [ExercisesAnswerAnalysisCell cellWithTableView:tableView];
        [cell setModel:self.currentItemModel];
        cell.updateCorrectCellFrame = ^{
            weakSelf.isFinishCorrect = YES;
            [weakSelf finishRefreshTableView];
        };
        cell.updateAnlyzeCellFrame = ^{
            weakSelf.isFinishAnlzy = YES;
            [weakSelf finishRefreshTableView];
        };
        
        return cell;
    }
    
    return [UITableViewCell new];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 3) {
        return 8.0f;
    }
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 3) {
        UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 8)];
        v.backgroundColor = RGBA(248, 248, 248, 1);
        return v;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

#pragma mark - ExercisesQuqestionChoiceItemCellDelegate
- (void)updateTableViewFrame{
    self.isFinishItem = YES;
    [self finishRefreshTableView];
}
- (void)selectedChoiceWithModel:(ExercisesQuestionChoiceItemModel *)model{
    
    __block NSInteger lastIndex = -1;

    [self.currentItemModel.items enumerateObjectsUsingBlock:^(ExercisesQuestionChoiceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 判断是否有选中
        if (obj.isSelected && ![obj.prefix isEqualToString:model.prefix]) {
            obj.isSelected = NO;
            lastIndex = idx;
        }
    }];
    if (lastIndex != -1) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lastIndex inSection:2];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }

    // 判断是否选中
    if (model.isSelected) {
        self.currentItemModel.isMake = @1;
        // 移除定时器
        [self endTimer];
        [[NSNotificationCenter defaultCenter]postNotificationName:NEXTQUESTIONPAGE object:nil];
    }

}

- (void)finishRefreshTableView{
    if (self.currentItemModel.answerItem == nil) {
        if (self.isFinishItem && self.isFinishTitle) {
            [CATransaction begin];
            [CATransaction setCompletionBlock:^{
                self.isFinishItem = NO;
                self.isFinishTitle = NO;
            }];
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
            [CATransaction commit];
        
        }
    }else{
        if (self.isFinishItem && self.isFinishTitle && self.isFinishAnlzy && self.isFinishCorrect) {
            [CATransaction begin];
            [CATransaction setCompletionBlock:^{
                self.isFinishItem = NO;
                self.isFinishTitle = NO;
                self.isFinishAnlzy = NO;
                self.isFinishCorrect = NO;
            }];
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
            [CATransaction commit];
        }
    }
}



@end
